package top.xunfong.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import top.xunfong.common.core.exception.ServiceException;
import top.xunfong.system.entity.SysUser;
import top.xunfong.system.entity.dto.RegisterDTO;
import top.xunfong.common.core.domain.model.LoginUserInfo;
import top.xunfong.system.mapper.SysUserMapper;
import top.xunfong.system.service.SysUserService;
import org.springframework.stereotype.Service;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Override
    public LoginUserInfo getUserInfo(String username) {
        SysUser sysUser = lambdaQuery().eq(SysUser::getUserName, username)
                .last("limit 1")
                .one();
        return BeanUtil.copyProperties(sysUser, LoginUserInfo.class);
    }

    @Override
    public void register(RegisterDTO dto) {
        // 检查用户名或者手机号是否存在
        SysUser one = lambdaQuery()
                .and(x -> x.eq(SysUser::getUserName, dto.getUserName())
                        .or()
                        .eq(SysUser::getPhonenumber, dto.getPhonenumber()))
                .last("limit 1").one();
        if (ObjectUtil.isNotNull(one)) {
            throw new ServiceException("用户名已存在");
        }
        SysUser sysUser = BeanUtil.copyProperties(dto, SysUser.class);
        sysUser.setNickName(sysUser.getUserName());
        sysUser.setPassword(BCrypt.hashpw(dto.getPassword()));
        save(sysUser);
    }
}